#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stack_link.h"

#define MAXSIZE 1024
/*运算符计算
 *
 *
 */

	static void compute(link_head *num,int op)
{
	Datatype n1,n2,n;
	Pop_Stack(num,&n2);
	Pop_Stack(num,&n1);
	switch(op)
	{
		case '+':
			n = n2 + n1;
			break;
		case '-':
			n = n1 - n2;
			break;
		case '*':
			n = n2 * n1;
			break;
		case '/':
			n = n1 / n2;
			break;
		case '%':
			n = n1 % n2;
			break;
		default:
			exit(1);
	}
	Push_Stack(num,n);
}

/*获取各符号优先级
 *
 *
 *
 *
 */

	int get_pri(int op)
{
	switch(op)
	{
		case '(':
			return 2;
		case '*':
		case '/':
		case '%':
			return 1;
		case '+':
		case '-':
			return 0;
	}

}












	int main()
{
	link_head *op = NULL;
	link_head *num = NULL;
	Init_Stack(&op);
	Init_Stack(&num);
	
	char arr[MAXSIZE] = {0};
	printf("Please Enter Expresion:\n");
	gets(arr);
	int len = strlen(arr);
	int flag;
	int n;
	for(int i = 0;i < len;i++)
	{
/*数字入栈
 *
 *
 */		
		while(arr[i] >= '0' && arr[i] <= '9')	
		{
			n = n*10 + arr[i] - '0';
			i++;
			flag = 1;
		}
		if(flag)
		{
			Push_Stack(num,n);
			n = 0;
			flag = 0;
		}
		if(arr[i] == '+' || arr[i] == '-' || arr[i] == '*' || arr[i] == '/' || arr[i] == '%' || arr[i] == '(' || arr[i] == ')')
		{
			switch(arr[i])
			{
//左括号直接入栈				
				case '(':
					{
						Push_Stack(op,arr[i]);
						break;
					}
//处理右括号，将左括号之后的运算符全部出栈，最后出栈左括号					
				case ')':
					{
						int temp;
						GetTop_Stack(op,&temp);
						
						while(temp != '(')
						{
							Pop_Stack(op,&temp);
							compute(num,temp);
							GetTop_Stack(op,&temp);
						}
						Pop_Stack(op,&temp);
						break;
					}
//处理其他运算符					
				case '+': case '-':	
				case '*': case '/': case '%':
					{
//符号栈为空时直接入栈						
						int old_op;
						if(IsEmpty_Stack(op))
						{
							Push_Stack(op,arr[i]);
							break;
						}
						
						GetTop_Stack(op,&old_op);
//优先级高直接入栈						
						if(get_pri(arr[i]) > get_pri(old_op))
						{
							Push_Stack(op,arr[i]);
						}
						else
						{
//优先级低时，等其他符号全部出栈再入栈							
							while(get_pri(arr[i]) <= get_pri(old_op))
							{
								if(old_op == '(')
									break;
								Pop_Stack(op,&old_op);
								compute(num,old_op);
								if(IsEmpty_Stack(op))
								{
									break;
								}
								GetTop_Stack(op,&old_op);
							}
								Push_Stack(op,arr[i]);
						}
						break;
					}
			
			
			}
		
		}
	}
//当运算符栈中还有符号时，进行出栈计算	
	int old_op;
	while(IsEmpty_Stack(op) == 0)
	{
		Pop_Stack(op,&old_op);
		compute(num,old_op);
	}
//最后栈顶元素即为结果	
	printf("result = %d\n",num->top->data);
		
	Destroy_Stack(op);
	Destroy_Stack(num);
	exit(0);
}
